 <meta charset="utf-8">
 <script src="https://imgcache.qq.com/open/qcloud/video/vcplayer/TcPlayer-2.3.3.js" charset="utf-8"></script>
 <div class="card" id="biz_deviceVedioMonitor_conatainer" style="padding-bottom: 0px;">
   
 <div class="card">
 	<div class="card-body">
 	<div class="row">
 	  <div class="col-md-3" style="width: 0px;">
              <div class="form-group row">
				<label for="example-search-input" class="col-md-3 col-form-label">报警设备</label>
					<div class="col-md-9">
					  <input class="form-control" type="search"  v-model="deviceNum">
					</div>
			  </div>
			  
			  <div class="card">
                          <div class="card-body">
        					<h4 class="header-title">报警消息列表</h4>
                                    <div class="" style="max-height: 600px;overflow-y: scroll;">
                                            <div class="alert alert-danger" role="alert"  style="cursor:pointer"
                                            	 v-for="(message,index) in messageList " v-on:click="loadMessage(message)">
                                               {{message.content}}
                                            </div>
                                        </div>
                            </div>
                 </div>
                                    
 	  </div>
 	  
 	    <div class="col-md-9" >
 	     <div class="row">
		 	  
		 	  <div class="col-md-6" >
		 	  	<h4 class="header-title">证据图片</h4>
		 	  		 <div class="card"  v-for="(imageUrl,index) in nowMessageImages ">
		                    <img class="card-img-top img-fluid" v-bind:src="imageUrl"  style="max-height: 500px" ><!-- -->
		              </div>
		 	  </div>
		 	  
		 	  
		 	      <div class="col-md-6">
		 	      <h4 class="header-title">证据视频</h4>
		 	  		<div class="card"  v-for="(videoUrl,index) in nowMessageVideos " >
		                  <video  autoplay="autoplay" width="500px" height="300px" max-height=500px ><!-- --> 
						    <source  v-bind:src="videoUrl" type="video/mp4">
						</video>
		             </div>
		 	   </div>
 	   
 	     </div>
 	     
 	     <div class="row">
		 	     <div class="col-md-4"  v-for="( channel , index ) in channels "  >
		 	     <div class="button-items" v-if="nowMessageVideos && nowMessageVideos.length>0 ">
		 	      		<button type="button" class="btn  btn-link waves-effect waves-light" disabled>通道:{{channel}}</button>
		                <button type="button" class="btn btn-outline-success waves-effect waves-light" v-on:click="startLive(channel)">播放</button>
		                &nbsp; &nbsp; &nbsp; &nbsp;
		                <button type="button" class="btn btn-outline-danger waves-effect waves-light"  v-on:click="stoptLive(channel)">停止</button>
		          </div>
		 	  		<div class="card"  v-for="( videoUrl , index) in nowMessageVideos " >
		                 <!--  <video   >
						    <source  v-bind:src="videoUrl" type="video/mp4">
						</video> -->
						
						<div id="id_test_video" style="width:100%; height:auto;"></div>
		             </div>
		 	   </div>
 	   
 	     </div>
 	     
 	     </div>
 	
 	
 	   
 	  
 	</div>
 	</div>
 	</div>
 	
 </div>
<script>
var vm=new Vue({  
	  el: '#biz_deviceVedioMonitor_conatainer', 
	  data:{
		  websocket: null,
		  lockReconnect: false,
		  userId:1,
		  tt:null,
		  path : '127.0.0.1:88',
		  bizType:'2',
		  
		  deviceNum: null,
		  channels: ['0000'],
		  
		  messageList:[],
		  nowMessage:{},
		  nowMessageImages:[],
		  nowMessageVideos:[],
		  
		  channelLive:[],
		  
		  channelReqMap:{},
		  channelReqRetryCountMap:{},
		  
		  interval:null,
		  requestHeartBeatStared: false,
	      bus:new Vue()
	  },
	  mounted:function(){
		 var _this=this;
		 _this.createWebSocket();
	  },
	  destroyed: function(){
		  var _this=this;
		  console.log("destroyed",_this.interval);
		  clearInterval(_this.interval);
	  },

    methods: {
    	startLive: function (channelId) {
    		var _this=this;
    		if(!_this.deviceNum){
    			alertSwal.warningText("没有设备消息");
    			return ;
    		}
    		var requestId = _this.generateUUID();
    		var url="/api/user/live/ws/startLive/"+_this.deviceNum+"/"+channelId+"/"+requestId+"";
    		_this.channelReqMap[channelId]=requestId;
    		
    		zfesAjax.ajaxJson(url,{}, function(data){
    			console.log("startLive",data);
    			
    			/* setTimeout(function(){  
    				_this.loadLiveUrl(channelId);
    			}, 500); */
    			
    			
    			if(!_this.requestHeartBeatStared){
    				_this.interval = setInterval(() => {
    					_this.requestHeartBeat();
                     }, 3000);
    				_this.requestHeartBeatStared=true;
    			}
    		
    			
    		});
      },
      stoptLive: function(channelId){
		    var _this=this;
		    var requestId=_this.channelReqMap[channelId];
		    delete  _this.channelReqMap[channelId];
		    console.log("channelReqMap",_this.channelReqMap);
	  		var url="/api/user/live/ws/stopLive/"+_this.deviceNum+"/"+channelId+"/"+requestId+"";
	  		zfesAjax.ajaxJson(url,{}, function(data){
	  			alertSwal.successText(data.message);
	      	})
	    },
	    loadLiveUrl: function(channelId){
    		var _this=this;
    		 var requestId=_this.channelReqMap[channelId];
    		var url="/api/user/live/ws/loadVideoUrl/"+_this.deviceNum+"/"+channelId+"/"+requestId+"";
    		zfesAjax.ajaxJson(url,{}, function(data){
    			console.log("-succ-loadLiveUrl:",data);
				 doPlay(data.data.liveUrl);
				
        	},function(data){
        		console.log("-err-loadLiveUrl:",data);
        		setTimeout(function(){ 
        			if(!_this.channelReqRetryCountMap[channelId]){
        				_this.channelReqRetryCountMap[channelId]=1;
        			}
        			var retryCount=_this.channelReqRetryCountMap[channelId];
        			
        			if(retryCount > 5){
						alertSwal.warningText("重试加载超过5次，放弃播放");
						return;
					}
    				_this.loadLiveUrl(channelId);
    				_this.channelReqRetryCountMap[channelId]=retryCount+1;
    				
    			}, 2000);
        		
        	})
     	 },
     	 
	    requestHeartBeat: function (channelId,requestId) {
    		var _this=this;
    		if(Object.keys(_this.channelReqMap).length == 0){
    			console.log("---channelReqMap--null--return---");
    			return;
    		}
    		var url="/api/user/live/ws/liveRequestHeartBeat/"+_this.deviceNum+"";
    		zfesAjax.ajaxJson(url,_this.channelReqMap, function(data){
    			//console.log("---requestHeartBeat---",data);
    		})
    	},
    	
    	loadMessage: function(message){
    		 var _this=this;
    		if(_this.nowMessage!= message.id){
    			_this.nowMessage=message;
    			_this.nowMessageImages=[];
    			_this.nowMessageVideos=[];
    			_this.channelReqMap={};
    			_this.channelReqRetryCountMap={};
    			_this.interval=null;
    			_this.requestHeartBeatStared=false;
    			  
    			var ajaxUrl = "/api/user/message/loadMsgInfo/"+message.id;
 			    zfesAjax.ajaxTodo(ajaxUrl, {}, function(data) {
 			    	 console.log(data);
 			    	 var images=data.data.massage.images;
 			    	 images.forEach((item,index,array)=>{
 			    			var imageId=item.id;
	 			    		 zfesAjax.ajaxTodo("/api/user/message/loadMsgImageUrl/"+imageId, {}, function(data) {
	 			    			_this.nowMessageImages.push(data.data.imgUrl);
	 			    			console.log("nowMessageImages",_this.nowMessageImages);
	 		 				});
 			    	 });
 			    	 var videos=data.data.massage.vedios;
 			    	 videos.forEach((item,index,array)=>{
			    			var videoId=item.id;
 			    		 zfesAjax.ajaxTodo("/api/user/message/loadMsgVedioUrl/"+videoId, {}, function(data) {
 			    			_this.nowMessageVideos.push(data.data.vedioUrl);
 			    			console.log("nowMessageVideos",_this.nowMessageVideos);
 		 				});
			    	 });
 			    	 
 				});
    		}
    		
    	},
    	
    	initWebsocket: function(){
    		 var _this=this;
    		 
    		_this.websocket.onopen = function(event) {
    	        console.log("WebSocket:已连接");
    	        console.log(event);
    	    };
    	    _this.websocket.onmessage = function(event) {
    	        var data = JSON.parse(event.data);
    	        console.log("WebSocket:收到一条消息-form", data);
    	        if("onMessage" == data.wsfun){
        	         if(_this.deviceNum!= data.data.deviceNum){
        	        	 _this.messageList=[];
        	         }
        	         _this.deviceNum=data.data.deviceNum;
        	         console.log("-onMessage--WebSocket:deviceNum:",  _this.deviceNum);
        	         _this.messageList.push({"id":data.data.messageId,"content":data.data.messageContent});
        	         console.log("-onMessage--WebSocket:messageList:",   _this.messageList);
    	        }
    	        if("onStartLive"== data.wsfun){
    	        	 console.log("-onStartLive--:", data.data.channelId);
    	        	var channelId=data.data.channelId
       	          _this.loadLiveUrl(channelId);
   	            }
    	        
    	         
    	    };
    	    _this.websocket.onerror = function(event) {
    	        console.log("WebSocket:发生错误 ");
    	        console.log(event);
    	        _this.reconnect();
    	    };
    	    _this.websocket.onclose = function(event) {
    	        console.log("WebSocket:已关闭");
    	        console.log(event);
    	        _this.reconnect();
    	    }
    	},
    	createWebSocket: function(){
	   		 var _this=this;
	   		  try{
	   		        if ('WebSocket' in window) {
	   		        	_this.websocket = new WebSocket("ws://" + _this.path + "/wsz?userId=" + _this.userId+"&&bizType="+_this.bizType+"");
	   		            _this.initWebsocket();
	   		        } else if ('MozWebSocket' in window) {
	   		        	_this.websocket = new MozWebSocket("ws://" + _this.path + "/wsz?userId=" + _this.userId+"&&bizType="+_this.bizType+"");
	   		        } else {
	   		        	_this.websocket = new SockJS("http://" + _this.path + "/wsz/sockjs?userId=" + _this.userId+"&&bizType="+_this.bizType+"");
	   		        }
	   		    } catch(e){
	   		        console.log(e);
	   		        _this.reconnect();
	   		    }
	   	},
    	reconnect: function() {
    		var _this=this;
    	    if(_this.lockReconnect) {
    	        return;
    	    };
    	    _this.lockReconnect = true;
    	     _this.tt && clearTimeout(_this.tt);  //没连接上会一直重连，设置延迟避免请求过多
    	     _this.tt = setTimeout(function () {
    	    	 _this.createWebSocket();
    	    	 _this.lockReconnect = false;
    	    }, 4000);
    	},
    	generateUUID: function () {
	        var d = new Date().getTime();
	        if (window.performance && typeof window.performance.now === "function") {
	            d += performance.now(); //use high-precision timer if available
	        }
	        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
	            var r = (d + Math.random() * 16) % 16 | 0;
	            d = Math.floor(d / 16);
	            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	        });
	        return uuid;
	    }
	  
   }

});
function doPlay(url){
	console.log("==doPlay==url=",url);
	$('#id_test_video').html("");
	  var player = new TcPlayer('id_test_video', {
	    	//"m3u8": "http://1304320487.vod2.myqcloud.com/beab3ec2vodcq1304320487/919b4b0b5285890811023386269/f0.mp4", //请替换成实际可用的播放地址
	    	"m3u8": url,//"http://47.92.196.10:8080/live/xz2.flv",
	    	//"m3u8": "http://47.92.196.10:8080/live/xz2.flv",
	    	"live": true,
	    	"x5_type": 'h5',
	    	"preload": true,
	    	"autoplay" : true,      //iOS 下 safari 浏览器，以及大部分移动端浏览器是不开放视频自动播放这个能力的
	    	//"poster" : "http://1304320487.vod2.myqcloud.com/beab3ec2vodcq1304320487/919b4b0b5285890811023386269/5285890811023386272.jpg",
	    	"width" :  '480',//视频的显示宽度，请尽量使用视频分辨率宽度
	    	"height" : '320',//视频的显示高度，请尽量使用视频分辨率高度
	    	"wording": {
	    	    2032: "请求视频失败，请检查网络",
	    	    2048: "请求m3u8文件失败，可能是网络错误或者跨域问题"
	    	},
	    	 "listener": function(e) { //监听事件
	                 if (e.type == "fullscreen") { //视频播放全屏可切换横屏
	                     if (e.detail.isFullscreen == true) {
	                         plus.screen.unlockOrientation("landscape-primary"); //横屏 mui写法
	                     } else if (e.detail.isFullscreen == false) {
	                         plus.screen.lockOrientation("portrait-primary");//强制竖屏 mui写法
	                     }
	                 }
	                 if(e.type == 'load') { //加载完事件
	                	 setInterval(() => {
	                		// player.togglePlay();
	                     }, 10*1000);
	                 
	     				//解决微信浏览器脱离文档流播放的问题；
	     				//TCPlayerLite文档设置"x5_type": "h5"在安卓微信浏览器不生效，以下代码可解决：
	     				//document.querySelector('id_test_video').setAttribute('x5-video-player-type', 'h5-page');
	     				//document.querySelector('id_test_video').setAttribute('x5-video-player-fullscreen', 'false');
	     				//document.querySelector('id_test_video').setAttribute('x5-video-orientation', 'portrait');
	     			}	
	    		 }
	    		 
	    	});
}
</script>


